package edu.gyc.appshiro.service.impl;

import edu.gyc.appshiro.dao.PermissionDao;
import edu.gyc.appshiro.dao.UserRoleDao;
import edu.gyc.appshiro.model.User;
import edu.gyc.appshiro.dao.UserDao;
import edu.gyc.appshiro.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.gyc.appshiro.shiro.MakePassword;
import edu.gyc.appshiro.vo.PermissionVo;
import edu.gyc.appshiro.vo.UserRoleVo;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ls
 * @since 2021-02-02
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

@Autowired
    UserRoleDao userRoleDao;

    @Override
    public Set<UserRoleVo> getUserRoles() {
        List<UserRoleVo> userRoles=userRoleDao.getUserRoles();
        Set<UserRoleVo> userRoleVoSet = new LinkedHashSet<>();
        //利用Set获取有多少个user的集合
        for (UserRoleVo ur : userRoles) {
            userRoleVoSet.add(ur);
        }

        for (UserRoleVo userRoleVo : userRoleVoSet) {
            if (userRoleVo.getDescription() != null) {//用户可能没有分配角色
                userRoleVo.getRoleSet().add(userRoleVo.getDescription());
            }

            for (UserRoleVo t : userRoles) {
                if (userRoleVo.getUsername().equals(t.getUsername())) {
                    if (userRoleVo.getDescription() != null) {
                        if(!userRoleVo.getDescription().equals(t.getDescription())){

                            userRoleVo.getRoleSet().add(t.getDescription());
                        }
                    }

                }
            }

            userRoleVo.setRolenames(userRoleVo.getRoleSet().toString());

        }

        return userRoleVoSet;
    }

    @Override
    public boolean newPassword(Integer uid,String oldpass,String salt, String newpass) {
        String tempPass = MakePassword.make(oldpass, salt);
        User user=getById(uid);
        String oldSecretPass=user.getPassword();
        if (tempPass.equals(oldSecretPass)) {
            String newSalt=RandomStringUtils.randomAlphabetic(6);
            tempPass=MakePassword.make(newpass, newSalt);
            user.setPassword(tempPass);
            user.setSalt(newSalt);
            saveOrUpdate(user);
            return true;

        }else {
            return false;
        }

    }
}
